package com.yq.spbYq.controller;

import com.yq.spbYq.WasteLog;
import com.yq.spbYq.service.WasteLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/wasteLogs")
public class WasteLogController {

    @Autowired
    private  WasteLogService wasteLogService;

    // 插入一条记录
    @PostMapping
    public ResponseEntity<WasteLog> insertWasteLog(@RequestBody WasteLog wasteLog) {
        int result = wasteLogService.insertWasteLog(wasteLog);
        if (result > 0) {
            return ResponseEntity.ok(wasteLog);
        } else {
            return ResponseEntity.badRequest().body(null);
        }
    }

    // 根据ID删除记录
    @DeleteMapping("/{rId}")
    public ResponseEntity<Void> deleteWasteLogById(@PathVariable Integer rId) {
        int result = wasteLogService.deleteWasteLogById(rId);
        if (result > 0) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 更新记录
    @PutMapping("/{rId}")
    public ResponseEntity<WasteLog> updateWasteLog(@PathVariable Integer rId, @RequestBody WasteLog wasteLog) {
        wasteLog.setrId(rId); // 确保更新的ID与路径中的ID一致
        int result = wasteLogService.updateWasteLog(wasteLog);
        if (result > 0) {
            return ResponseEntity.ok(wasteLog);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据ID查询记录
    @GetMapping("/{rId}")
    public ResponseEntity<WasteLog> selectWasteLogById(@PathVariable Integer rId) {
        WasteLog wasteLog = wasteLogService.selectWasteLogById(rId);
        if (wasteLog != null) {
            return ResponseEntity.ok(wasteLog);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 查询所有记录
    @GetMapping
    public ResponseEntity<List<WasteLog>> selectAllWasteLogs() {
        List<WasteLog> wasteLogs = wasteLogService.selectAllWasteLogs();
        return ResponseEntity.ok(wasteLogs);
    }
}